<template>
    <div class="loan-out-detail-other" v-if='pageLoaded'>
        <!-- wrapper -->
        <div class="wrapper">
            <div class="loan-detail-main">
                <div class="loan-detail-number">
                    <p class="loan-detail-number__number">编号: {{ number }}</p>
                </div>
                
                <div class="loan-detail-money">
                    <div class="loan-detail-money__total">
                        <p class='text'>借款总额</p>
                        <span class='number purple'>{{detail.lendAmountFrom | toYuan}}~{{detail.lendAmountTo | toYuan}}元</span>
                    </div>
                    <ul class="loan-detail-money__list">
                        <li class="loan-detail-money__item" v-if='detail.daysType == "DAY"'>
                            <span class='persent'>{{daysTransform(detail.lendDaysFrom,detail.lendDaysTo,'day')}}</span>
                            <p>可借时长</p>
                        </li>
                        <li class="loan-detail-money__item" v-else>
                            <span class='persent'>{{daysTransform(detail.lendDaysFrom,detail.lendDaysTo,'period')}}</span>
                            <p>可借时长</p>
                        </li>
                        <li class="loan-detail-money__item">
                            <span class='persent'>{{detail.yearRate/100}}%</span>
                            <p>年利率</p>
                        </li>
                        <li class="loan-detail-money__item">
                            <span class='persent'>{{detail.serviceFeeRate/100}}% | {{detail.serviceFee/100}}元起</span>
                            <p>服务费</p>
                        </li>
                    </ul>
                </div>
                <div class="loan-detail-info">
                    <ul class="card__info">
                        <li class="card__info-item">发布日期：{{ detail.createdAt | dateFormat  }}</li>
                        <li class="card__info-item">还款方式：{{ detail.repayWayStr }}</li>
                        <li class="card__info-item">所有人可见：{{ detail.public | booleanToStr }}</li>
                    </ul>
                    <!-- <p class="card__info-item full">必备信用资料：{{ detail.myCreditMaterialInfo || placeholder }}</p> -->
                    <!-- <p class="card__info-item full">补充说明：{{ detail.addSay || placeholder }}</p> -->
                    <div class="detail-other-recent full">
                        <!-- <p class="data">
                            <span>{{ detail.applyCount }}</span>
                            人申请  |  {{passPersent(detail.passCount,detail.rejectCount)}}%通过  |  {{detail.dealAvgTime | timeToHours}}小时处理
                        </p> -->
                        <p class="data">
                            <span>{{ detail.applyCount }}</span>
                            人申请  |  {{detail.dealAvgTime | timeToHours}}小时处理
                        </p>
                        <!-- <p class="recent">最近成交：{{detail.recentSuccessDate | dateFormat}}</p> -->
                    </div>
                </div>
            </div>
        </div>
            
        <!-- footer -->
        <footer class="single-button">
            <span class="button transparent" @click='goBack()' v-if='detail.isMyApplyBorrow || storeUserInfo.user.bizRole == "B"'>返回</span>
            <span class="button" @click='apply' v-else>马上申请</span>
        </footer>

        <confirm 
            v-if='userInfo.user'
            :show='show_contact_add'
            @close='show_contact_add = false'
            @confirm='applyContact'
            :tips='`需要发送申请给${userInfo.user.realName}`'
            title='添加联系人申请'>
                <textarea class="confirm-textarea" placeholder="例如: 我想向你借款" rows='2' v-model='applyReason'></textarea>
        </confirm>

        <confirm 
            :show='show_modal_close_apply'
            @close='show_modal_close_apply = false'
            @confirm='closeApply'
            title='确认关闭申请'
            tips='是否确认关闭申请'></confirm>
    </div>
</template>

<script>
    import { Promise } from 'es6-promise'
    import confirm from '../components/Confirm.vue'
    import countDown from '../components/CountDown.vue'
    import toYuan from '../filters/filter-toYuan'
    import dateFormat from '../filters/filter-dateFormat'
    import booleanToStr from '../filters/filter-booleanToStr'
    import { timeToHours } from '../filters/filter-timeFormat'
    import { convertRequestURL } from '../utils/utils'
    import  { mapGetters, mapActions }  from 'vuex'
    import { allApi, loanInApi, loanOutApi, contactApi } from '../api/api'
    import moment from 'moment'

    export default {
        components:{
            confirm,
            countDown,
        },
        filters:{
            toYuan,
            dateFormat,
            booleanToStr,
            timeToHours
        },
        data() {
            return {
                placeholderImg:require('../images/loading_1.png'),
                placeholder:'--',
                pageLoaded:false,
                applyReason:'',
                number:this.$route.params.number,
                show_modal_close_apply:false,
                show_contact_add:false,
                detail:{},
                userInfo:{},
                show_modal_loan_detail:false,
            }
        },
        computed:{
            ...mapGetters([
                'msgTip',
                'localInfo'
            ]),
            storeUserInfo(){
                return this.localInfo.userInfo
            },
            currentPage(){
                if(_.isEmpty(this.listInfo)) return 1
                return this.listInfo.pageNum
            },
            hasUserCount(){
                return !_.isEmpty(this.userCount)
            },
            noEditObject(){
                return _.isEmpty(this.editObject)
            },
            noInvoiceInfo(){
                return _.isEmpty(this.invoiceInfo)
            }
        },
        methods:{
            // actions
            ...mapActions([
                'showLoading',
                'hideLoading',
                'setMsgTip',
                'removeLoanInForm'
            ]),

            // filters
            goContactDetail(id){
                this.$router.push({
                    name:'contact-detail',
                    params:{
                        id:id
                    }
                })
            },
            timestampToDate(timestamp){
                if(!timestamp) return this.placeholder
                return moment(timestamp).format('YYYY-MM-DD')
            },

            // function

            
            daysTransform(from,to,type){
                let suffix
                let fromStr = from
                let toStr = to

                if(type == 'day') suffix = '天'
                else suffix = '期'

                if(from >= 30 && type == 'day'){
                    suffix = '个月'
                    fromStr = from / 30 
                    toStr = to / 30 

                }
                if(from == to){
                    return fromStr + suffix
                }
                else{
                    return fromStr + suffix + '~' + toStr + suffix
                }
            },
            goBack(){
                console.log(this.$router)
                this.$router.back()
            },
            add(){
                if(!this.storeUserInfo.isPay || this.storeUserInfo.isExpired){
                    this.setMsgTip({
                        text:'请先完成信用报告',
                        type:'info'

                    })
                    return
                }
                
                this.showLoading()
                contactApi.judge({
                    mobile:this.userInfo.user.uuid
                })
                .then(result=>{
                    this.show_contact_add = true
                    this.hideLoading()
                })
                .catch(error => {
                    console.error(error)
                    this.hideLoading()
                })
            },
            applyContact(){
                this.showLoading()
                contactApi.apply({
                    mobile:this.userInfo.user.uuid,
                    applyReason:this.applyReason
                })
                .then(result=>{
                    this.hideLoading()
                    this.show_contact_add = false
                })
                .catch(error => {
                    console.error(error)
                    this.hideLoading()
                })
            },
            goRouter(name){
                this.$router.push({
                    name:name
                })
            },
            goReportDetail(){
                if(!this.userInfo.creditReport){
                    this.setMsgTip({
                        text:'该用户暂无信用报告！',
                        type:'warn'
                    })
                    return
                }
                this.$router.push({
                    name:'user-credit-report-detail',
                    params:{
                        no:this.userInfo.creditReport.creditReportNo
                    }
                })
            },
            apply(){
                this.removeLoanInForm()
                // this.addContact()
                this.$router.push({
                    name:'loan-in-want-index',
                    params:{
                        number:this.number
                    }
                })
            },
            goChat(id){
                if(!this.storeUserInfo.isPay || this.storeUserInfo.isExpired){
                    this.setMsgTip({
                        text:'请先完成信用报告',
                        type:'info'

                    })
                    return
                }

                this.showLoading()
                contactApi.im({
                    uuid:id
                })
                .then(result=>{
                    this.hideLoading()
                    let info = result.info
                    let myAccid = info.myAccid
                    let accid = info.accid
                    let token = info.token
                    location.href = convertRequestURL(`?token=${token}&uid=${myAccid}#/chat/p2p-${accid}`,'chat')
                })
                .catch(error => {
                    console.error(error)
                    this.hideLoading()
                })
            },
            goLoanDetail(id){
                this.$router.push({
                    name:'loan-detail',
                    params:{
                        id:id
                    }
                })
                this.$ga.event({
                  eventCategory: 'debt _v',
                  eventAction: 'click',
                  eventLabel: '负债详情点击次数'
                })
                allApi.onEvent({
                    eventType:'track_click',
                    eventName:'debt _v',
                    eventDescr:'负债详情点击次数',
                    eventValue:JSON.stringify({
                        uuid:id
                    }),
                })
            },
            close(){
                loanOutApi.detailOther({
                    lendNo:this.number
                })
                .then(result=>{
                    this.detail = result
                })
                .catch(error=> {
                    console.log(error);
                    this.hideLoading()
                });
            },
            closeApply(){
                loanInApi.close({
                    borrowNo:this.detail.borrowNo
                })
                .then(result=>{
                    this.hideLoading()
                    this.show_modal_close_apply = false
                    history.go(-1)
                })
                .catch(error=> {
                    console.log(error);
                    this.hideLoading()
                    this.show_modal_close_apply = false
                });
            },
            passPersent(pass,reject){
                if(pass == 0) return 0
                return pass/(pass+reject)*100
            },
            goRepayment(){
                this.$router.push({
                    name:'loan-in-repayment'
                })
            },
            goSuccess(){
                this.$router.push({
                    name:'loan-in-success'
                })
            },
            test(){
                console.log(1)
            },
            goPay(){
                this.payStatus = true
                console.log(1)
            },
            goDetail(item){
                this.$router.push({
                    name:'user-detail',
                    params:{
                        id:item.userId,
                    }
                })
            },
            getDetail(){
                return loanOutApi.detailOther({
                    lendNo:this.number
                })
                .then(result=>{
                    this.detail = result
                })
            },
            getUserInfo(){
                return loanOutApi.userInfo({
                    lendNo:this.number
                })
                .then(result=>{
                    this.userInfo = result
                })
            },
        },
        created(){


            this.showLoading()
            Promise.all([this.getUserInfo(), this.getDetail()])
            .then(result=> {
                this.pageLoaded = true
                this.hideLoading()
            })
            .catch(error=> {
                console.error(error);
                this.pageLoaded = true
                this.hideLoading()
            });
        }
    }
</script>

<style lang="scss">
    @import "../sass/variables";
    @import "../sass/extends";
    @import "../sass/mixins";
    .loan-out-detail-other{
        .loan-detail-user__info{
            .name{
                display: flex;
                align-items: center;
                span{
                    display: block;
                    padding-right: 5px;
                }
            }
            .contact__button{
                font-size: 12px;
                padding-left: 10px;
                width: auto;
            }
        }
        .wrapper{
            padding-bottom: 100px;
        }
        .loan-detail-main{
            background-color: #fff;
            padding:0 24px;
            position: relative;
        }
        .detail-other-recent{
            padding: 16px 0;
            margin-top: 16px;
            border-top: 1px solid $sectionColor;
            @extend %font-caption;
            p{
                padding-bottom: 8px;
                span{
                    color:$orange;
                }
            }
        }
    }

</style>
